package com.moneyhelper.upms.rest;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.moneyhelper.message.email.EmailService;
import com.moneyhelper.message.model.AliyunSmsOneModel;
import com.moneyhelper.message.model.AliyunSmsSendDetailsModel;
import com.moneyhelper.message.model.MailMessageModel;
import com.moneyhelper.message.sms.AliyunSmsService;
import com.moneyhelper.oss.util.FileUploadUtil;
import com.wechat.service.account.dto.accountManage.Long2ShortLinkReqDTO;
import com.wechat.service.account.dto.accountManage.ParamsQRCodeCreateReqDTO;
import com.wechat.service.account.dto.accountManage.ParamsQRCodeCreateRespDTO;
import com.wechat.service.account.dto.customMenu.ConditionalMenuCreateReqDTO;
import com.wechat.service.account.dto.customMenu.MenuCreateParamReqDTO;
import com.wechat.service.account.dto.customMenu.MenuCreateReqDTO;
import com.wechat.service.account.dto.messageManage.templateMessage.TemplateMessage;
import com.wechat.service.account.starter.accountManage.Long2ShortLinkService;
import com.wechat.service.account.starter.accountManage.ParamsQRCodeService;
import com.wechat.service.account.starter.customMenu.*;
import com.wechat.service.account.starter.templateMessage.TemplateMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.*;

/**
 * @Author yanggld
 * @Date 2019/7/8-17:47
 * @Description
 */
@Slf4j
@RestController
public class TestRest {

	@Autowired
	private FileUploadUtil fileUploadUtil;

	@Autowired
	private AliyunSmsService aliyunSmsService;

	@Autowired
	private EmailService emailService;

	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;

	@GetMapping("/test/upload")
	public String uploadFile(@RequestParam String token){
//		String path = "C:\\Users\\admin\\Desktop\\分布式任务中心.png";
//		File file = new File(path);
//		return fileUploadUtil.uploadImageStream(file);
		return token;
	}

	@PostMapping("/test/upload")
	public String uploadFile2(@RequestParam MultipartFile file) throws Exception {
		InputStream inputStream = file.getInputStream();
		Snowflake snowflake = IdUtil.createSnowflake(1, 1);
		long id = snowflake.nextId();
		String name = file.getOriginalFilename();
		int lastIndexOf = name.lastIndexOf(".");
		String substring = name.substring(lastIndexOf);
		return fileUploadUtil.uploadImageByStream(inputStream,id+substring);
	}

	@GetMapping("/test/delete")
	public String delete(){
		return fileUploadUtil.deleteFileByName("xx");
	}

	@GetMapping("/test/deleteFileByUrl")
	public String deleteFileByUrl(@RequestParam String url){
		return fileUploadUtil.deleteFileByUrl(url);
	}

	@GetMapping("/test/sms/{phone}")
	public String sendSms(@PathVariable String phone){
		AliyunSmsOneModel oneModel = new AliyunSmsOneModel();
		oneModel.setPhoneNumber(phone);
		oneModel.setSignName("小星星");
		oneModel.setTemplateCode("SMS_170115954");
		JSONObject templateParamJson = new JSONObject();
		templateParamJson.put("code","123456");
		oneModel.setTemplateParam(templateParamJson);
		SendSmsResponse sendSmsResponse = null;
		try {
			sendSmsResponse = aliyunSmsService.sendOneSms(oneModel);
		} catch (ClientException e) {
			log.info("发送短息失败:{}",e.getErrMsg());
		}
		/**
		 * {
		 *     "bizId":"233406662738210200^0",
		 *     "code":"OK",
		 *     "message":"OK",
		 *     "requestId":"744A192C-DC55-4986-A99C-AC5099E3790D"
		 * }
		 */
		log.info("发送短信结果：{}",JSONObject.toJSONString(sendSmsResponse));
		if ("OK".equals(sendSmsResponse.getCode())) {
			log.info("**********短信发送成功*********");
		}

		AliyunSmsSendDetailsModel detailsModel = new AliyunSmsSendDetailsModel();
		detailsModel.setPhoneNumber(phone);
		detailsModel.setSendDate("20190710");
		QuerySendDetailsResponse querySendDetailsResponse = null;
		try {
			querySendDetailsResponse = aliyunSmsService.querySendDetails(detailsModel);
		} catch (ClientException e) {
			log.info("短信查询结果失败:{}",e.getErrMsg());
		}
		/**
		 * {
		 *     "code":"OK",
		 *     "message":"OK",
		 *     "requestId":"FAD47330-15D4-4905-A627-8459693A90C1",
		 *     "smsSendDetailDTOs":[
		 *         {
		 *             "content":"【小星星】验证码为：123456，您正在尝试变更重要信息，请妥善保管账户信息。",
		 *             "errCode":"DELIVERED",
		 *             "phoneNum":"19951761632",
		 *             "receiveDate":"2019-07-10 13:42:42",
		 *             "sendDate":"2019-07-10 13:42:35",
		 *             "sendStatus":3,
		 *             "templateCode":"SMS_170115954"
		 *         }
		 *     ],
		 *     "totalCount":"1"
		 * }
		 */
		log.info("短信查询结果：{}",JSONObject.toJSONString(querySendDetailsResponse));
		List<QuerySendDetailsResponse.SmsSendDetailDTO> smsSendDetailDTOs = querySendDetailsResponse.getSmsSendDetailDTOs();
		return JSONObject.toJSONString(querySendDetailsResponse);
	}

	@GetMapping("/test/email/send")
	public Boolean sendEmail(){
		MailMessageModel mailMessageModel = new MailMessageModel();
		mailMessageModel.setFrom("1433414364@qq.com");
		mailMessageModel.setToEmail("1433414364@qq.com");
		mailMessageModel.setSubject("小星星的主题");
		mailMessageModel.setTemplateName("index.ftl");

		Map<String,Object> params = new HashMap<>();
		params.put("name","小星星");
		params.put("sex",0);
		List<Map<String,Object>> friends = new ArrayList<>();
		Map<String,Object> friend = new HashMap<>();
		friend.put("name","小太阳");
		friend.put("age","www.baicu.com");
		friends.add(friend);
		params.put("friends",friends);

		mailMessageModel.setParams(params);
		return emailService.sendHtmlEmail(freeMarkerConfigurer,mailMessageModel);
	}


	@Autowired
	private ParamsQRCodeService paramsQRCodeService;

	@GetMapping("/test/reqCreateTempQRCode")
	public Object reqCreateTempQRCode(){
		ParamsQRCodeCreateReqDTO reqDTO = new ParamsQRCodeCreateReqDTO();
		reqDTO.setAction_name("QR_STR_SCENE");
		reqDTO.setScene_str("1234");
		ParamsQRCodeCreateRespDTO respDTO = paramsQRCodeService.reqCreateTempQRCode(reqDTO);
		return respDTO;
	}

	@GetMapping("/test/reqCreatePermQRCode")
	public Object reqCreatePermQRCode(){
		ParamsQRCodeCreateReqDTO reqDTO = new ParamsQRCodeCreateReqDTO();
		reqDTO.setAction_name("QR_LIMIT_STR_SCENE");
		reqDTO.setScene_str("4321");
		ParamsQRCodeCreateRespDTO respDTO = paramsQRCodeService.reqCreatePermQRCode(reqDTO);
		return respDTO;
	}

	@GetMapping("/test/showqrcode/{ticket}")
	public String showqrcode(@PathVariable String ticket){
		String path = "d:\\test.jpg";
		paramsQRCodeService.saveQRcode(ticket,path);
		return paramsQRCodeService.getQRCodeUrl(ticket);
	}

	@Autowired
	private Long2ShortLinkService long2ShortLinkService;

	@GetMapping("/test/toShort")
	public String toShort(){
		Long2ShortLinkReqDTO reqDTO = new Long2ShortLinkReqDTO();
		reqDTO.setLong_url("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQGM8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyX0pYYVlZZGtjUEMxMDAwMDAwN2wAAgRg7iVdAwQAAAAA");
		return long2ShortLinkService.toShort(reqDTO);
	}

	@Autowired
	private MenuCreateService menuCreateService;

	/**
	 * 创建菜单
	 * @return
	 */
	@GetMapping("/test/createMenu")
	public boolean createMenu(){
		MenuCreateReqDTO reqDTO = new MenuCreateReqDTO();
		List<MenuCreateParamReqDTO> buttonList = new ArrayList<>();
		// 一级菜单－
		MenuCreateParamReqDTO paramReqDTO1 = new MenuCreateParamReqDTO();
		paramReqDTO1.setType("click");
		paramReqDTO1.setName("今日歌曲");
		paramReqDTO1.setKey("V1001_TODAY_MUSIC");
		buttonList.add(paramReqDTO1);

		// 一级菜单二
		MenuCreateParamReqDTO paramReqDTO2 = new MenuCreateParamReqDTO();
		paramReqDTO2.setName("菜单");
		List<MenuCreateParamReqDTO> paramReqDTO2SubButtonList = new ArrayList<>();

		MenuCreateParamReqDTO paramReqDTO2_1 = new MenuCreateParamReqDTO();
		paramReqDTO2_1.setType("view");
		paramReqDTO2_1.setName("搜索");
		paramReqDTO2_1.setUrl("http://www.baidu.com");
		paramReqDTO2SubButtonList.add(paramReqDTO2_1);

		MenuCreateParamReqDTO paramReqDTO2_2 = new MenuCreateParamReqDTO();
		paramReqDTO2_2.setType("pic_photo_or_album");
		paramReqDTO2_2.setName("拍照或者相册发图");
		paramReqDTO2_2.setKey("rselfmenu_1_1");
		paramReqDTO2SubButtonList.add(paramReqDTO2_2);

		MenuCreateParamReqDTO paramReqDTO2_3 = new MenuCreateParamReqDTO();
		paramReqDTO2_3.setType("scancode_push");
		paramReqDTO2_3.setName("扫码推事件");
		paramReqDTO2_3.setKey("rselfmenu_0_1");
		paramReqDTO2SubButtonList.add(paramReqDTO2_3);

		MenuCreateParamReqDTO paramReqDTO2_4 = new MenuCreateParamReqDTO();
		paramReqDTO2_4.setType("scancode_waitmsg");
		paramReqDTO2_4.setName("扫码推事件2");
		paramReqDTO2_4.setKey("rselfmenu_0_2");
		paramReqDTO2SubButtonList.add(paramReqDTO2_4);

		MenuCreateParamReqDTO paramReqDTO2_5 = new MenuCreateParamReqDTO();
		paramReqDTO2_5.setType("pic_sysphoto");
		paramReqDTO2_5.setName("系统拍照发图");
		paramReqDTO2_5.setKey("rselfmenu_0_3");
		paramReqDTO2SubButtonList.add(paramReqDTO2_5);

		paramReqDTO2.setSub_button(paramReqDTO2SubButtonList);
		buttonList.add(paramReqDTO2);

		// 一级菜单三
		MenuCreateParamReqDTO paramReqDTO3 = new MenuCreateParamReqDTO();
		paramReqDTO3.setType("location_select");
		paramReqDTO3.setName("发送位置");
		paramReqDTO3.setKey("rselfmenu_2_0");
		buttonList.add(paramReqDTO3);

		reqDTO.setButton(buttonList);
		return menuCreateService.createMenu(reqDTO);
	}

	@Autowired
	private MenuQueryService menuQueryService;

	/**
	 * 查询菜单
	 * @return
	 */
	@GetMapping("/test/queryMenu")
	public JSONObject queryMenu(){
		return menuQueryService.queryMenu();
	}

	@Autowired
	private MenuDeleteService menuDeleteService;

	/**
	 * 删除菜单
	 * @return
	 */
	@GetMapping("/test/deleteMenu")
	public boolean deleteMenu(){
		return menuDeleteService.deleteMenu();
	}

	@Autowired
	private ConditionalMenuService conditionalMenuCreateService;

	/**
	 * 创建个性化菜单
	 * @return
	 */
	@GetMapping("/test/createConditionalMenu")
	public boolean createConditionalMenu(){
		if(true) {
			ConditionalMenuCreateReqDTO dto = new ConditionalMenuCreateReqDTO();
			List<MenuCreateParamReqDTO> buttonList = new ArrayList<>();
			// 一级菜单－
			MenuCreateParamReqDTO paramReqDTO1 = new MenuCreateParamReqDTO();
			paramReqDTO1.setType("click");
			paramReqDTO1.setName("广州天气");
			paramReqDTO1.setKey("V1001_TODAY_MUSIC");
			buttonList.add(paramReqDTO1);

			dto.setButton(buttonList);

			ConditionalMenuCreateReqDTO.MatchRule matchRule = new ConditionalMenuCreateReqDTO.MatchRule();
			matchRule.setCountry("中国");
			matchRule.setProvince("广东");
			matchRule.setCity("广州");
			dto.setMatchrule(matchRule);
			conditionalMenuCreateService.createConditionalMenu(dto);
		}
		if (true){
			ConditionalMenuCreateReqDTO dto = new ConditionalMenuCreateReqDTO();
			List<MenuCreateParamReqDTO> buttonList = new ArrayList<>();
			// 一级菜单－
			MenuCreateParamReqDTO paramReqDTO1 = new MenuCreateParamReqDTO();
			paramReqDTO1.setType("click");
			paramReqDTO1.setName("南京天气");
			paramReqDTO1.setKey("V1001_TODAY_MUSIC");
			buttonList.add(paramReqDTO1);

			dto.setButton(buttonList);

			ConditionalMenuCreateReqDTO.MatchRule matchRule = new ConditionalMenuCreateReqDTO.MatchRule();
			matchRule.setCountry("中国");
			matchRule.setProvince("江苏");
			matchRule.setCity("南京");
			dto.setMatchrule(matchRule);
			conditionalMenuCreateService.createConditionalMenu(dto);
		}
		return true;
	}

	/**
	 * 测试个性化菜单匹配结果
	 * @return
	 */
	@GetMapping("/test/matchMen")
	public Object matchMenu(){
		return conditionalMenuCreateService.matchMenu("ozdQz5oYofaAQbV7-WPP1L1shCns");
	}

	@Autowired
	private SelfMenuInfoService selfMenuInfoService;

	/**
	 * 获取自定义菜单配置接口
	 * @return
	 */
	@GetMapping("/test/getCurrentSelfMenuInfo")
	public Object getCurrentSelfMenuInfo(){
		return selfMenuInfoService.getCurrentSelfMenuInfo();
	}


	@Autowired
	private TemplateMessageService templateMessageService;
	/**
	 * 发送模板消息
	 * @return
	 */
	@GetMapping("/test/sendTemplateMessage")
	public Object sendTemplateMessage(){
		TemplateMessage msg = new TemplateMessage();
		msg.setTouser("ozdQz5oYofaAQbV7-WPP1L1shCns");
		msg.setTemplate_id("znVyKFui-YNBUb1P7yirEwtHIupNHAF4ZrFBZkT-H2Y");
		msg.setUrl("https://www.baidu.com");
		JSONObject data = new JSONObject();
		Map<String,Object> time = new HashMap<>();
		time.put("value","2019-07-13");
		time.put("color","#FF0000");
		data.put("time",time);
		Map<String,Object> content = new HashMap<>();
		content.put("value","自定义内容");
		content.put("color","#173177");
		data.put("content",content);
		msg.setData(data);
		return templateMessageService.sendTemplate(msg);
	}
}
